package com.ww.microrpc.netty.common;

import com.alibaba.fastjson.JSON;
import com.ww.microrpc.netty.ResponseHolder;
import com.ww.microrpc.netty.protocol.ResponseMessage;
import com.ww.microrpc.netty.exception.RpcClientException;
import com.ww.microrpc.netty.protocol.ErrorMessage;
import com.ww.microrpc.netty.protocol.Message;


/**
 * @author iiwan
 */
public class ConvertUtil {
    public static <T> T convertObject(Message response, Class<T> targetClass) {
        if (response == null) {
            return null;
        } else if (response instanceof ErrorMessage) {
            throw new RpcClientException(((ErrorMessage) response).getErrorMessage());
        } else if (response instanceof ResponseMessage) {
            ResponseMessage rr = (ResponseMessage) response;
            if (rr.getClass().getName().equals(targetClass.getName())) {
                return (T) rr;
            } else if (rr.getResult().getClass().isAssignableFrom(targetClass)) {
                return (T) rr.getResult();
            } else {
                String s = JSON.toJSONString(rr.getResult());
                return JSON.parseObject(s, targetClass);
            }
        }

        return null;
    }

    public static <T> ResponseHolder<T> convertObjectToHolder(Message response, Class<T> targetClass) {

        ResponseHolder<T> holder = new ResponseHolder<T>();

        if (response instanceof ResponseMessage) {
            Object result = ((ResponseMessage) response).getResult();
            holder.setResult((T) result);
        }

        return holder;
    }

}
